/**
 * 本地存储工具类
 * 用于管理用户学习进度、课程完成情况和成就系统
 * 使用 AsyncStorage 实现数据持久化
 */
import AsyncStorage from '@react-native-async-storage/async-storage';
import { userProgress, achievements } from '../data/lessons';

// 存储键名常量定义
const STORAGE_KEYS = {
  USER_PROGRESS: 'user_progress',        // 用户进度数据
  LESSONS_PROGRESS: 'lessons_progress',  // 课程完成进度
  ACHIEVEMENTS: 'achievements'           // 成就数据
};

/**
 * 初始化用户进度数据
 * 在用户首次使用应用时创建默认数据
 * @returns {Promise<void>}
 */
export const initializeUserProgress = async () => {
  try {
    // 检查是否已经存在用户进度数据
    const existingProgress = await AsyncStorage.getItem(STORAGE_KEYS.USER_PROGRESS);
    if (!existingProgress) {
      // 如果不存在，创建默认数据
      await AsyncStorage.setItem(STORAGE_KEYS.USER_PROGRESS, JSON.stringify(userProgress));
      await AsyncStorage.setItem(STORAGE_KEYS.ACHIEVEMENTS, JSON.stringify(achievements));
      console.log('用户进度数据初始化完成');
    }
  } catch (error) {
    console.error('初始化用户进度数据失败:', error);
    throw new Error('无法初始化用户数据，请检查存储权限');
  }
};

/**
 * 获取用户进度数据
 * @returns {Promise<Object>} 用户进度对象
 */
export const getUserProgress = async () => {
  try {
    const progress = await AsyncStorage.getItem(STORAGE_KEYS.USER_PROGRESS);
    if (progress) {
      const parsedProgress = JSON.parse(progress);
      // 确保数据结构完整，如果缺少字段则使用默认值
      return {
        ...userProgress,
        ...parsedProgress
      };
    }
    return userProgress;
  } catch (error) {
    console.error('获取用户进度数据失败:', error);
    return userProgress; // 返回默认数据
  }
};

/**
 * 更新用户进度数据
 * @param {Object} newProgress - 新的进度数据
 * @returns {Promise<Object>} 更新后的进度数据
 */
export const updateUserProgress = async (newProgress) => {
  try {
    // 验证数据有效性
    if (!newProgress || typeof newProgress !== 'object') {
      throw new Error('无效的进度数据');
    }
    
    const progressToSave = {
      ...newProgress,
      lastUpdated: new Date().toISOString() // 添加更新时间戳
    };
    
    await AsyncStorage.setItem(STORAGE_KEYS.USER_PROGRESS, JSON.stringify(progressToSave));
    console.log('用户进度数据更新成功');
    return progressToSave;
  } catch (error) {
    console.error('更新用户进度数据失败:', error);
    throw error;
  }
};

/**
 * 获取课程完成进度
 * @returns {Promise<Object>} 课程完成情况对象
 */
export const getLessonsProgress = async () => {
  try {
    const progress = await AsyncStorage.getItem(STORAGE_KEYS.LESSONS_PROGRESS);
    return progress ? JSON.parse(progress) : {};
  } catch (error) {
    console.error('获取课程进度数据失败:', error);
    return {};
  }
};

/**
 * 更新课程完成进度
 * @param {number} lessonId - 课程ID
 * @param {boolean} completed - 是否完成
 * @param {number} score - 课程得分（可选）
 * @returns {Promise<Object>} 更新后的课程进度
 */
export const updateLessonProgress = async (lessonId, completed = true, score = null) => {
  try {
    const currentProgress = await getLessonsProgress();
    const lessonProgress = {
      completed,
      completedAt: new Date().toISOString(),
      attempts: (currentProgress[lessonId]?.attempts || 0) + 1, // 记录尝试次数
      lastAttemptScore: score, // 最后一次得分
      bestScore: Math.max(score || 0, currentProgress[lessonId]?.bestScore || 0) // 最高得分
    };
    
    currentProgress[lessonId] = lessonProgress;
    await AsyncStorage.setItem(STORAGE_KEYS.LESSONS_PROGRESS, JSON.stringify(currentProgress));
    console.log(`课程 ${lessonId} 进度更新成功`);
    return currentProgress;
  } catch (error) {
    console.error('更新课程进度失败:', error);
    throw error;
  }
};

/**
 * 为用户添加经验值
 * @param {number} xpAmount - 要添加的经验值
 * @returns {Promise<Object>} 更新后的用户进度
 */
export const addXP = async (xpAmount) => {
  try {
    if (typeof xpAmount !== 'number' || xpAmount < 0) {
      throw new Error('无效的经验值数量');
    }
    
    const currentProgress = await getUserProgress();
    const newXP = currentProgress.totalXP + xpAmount;
    const newLevel = Math.floor(newXP / 100) + 1; // 每100XP一级
    
    // 检查是否升级
    const leveledUp = newLevel > currentProgress.level;
    
    const updatedProgress = {
      ...currentProgress,
      totalXP: newXP,
      level: newLevel,
      lastXPGain: xpAmount,
      lastXPGainTime: new Date().toISOString()
    };
    
    await updateUserProgress(updatedProgress);
    
    if (leveledUp) {
      console.log(`恭喜升级！新等级：${newLevel}`);
    }
    
    return { ...updatedProgress, leveledUp };
  } catch (error) {
    console.error('添加经验值失败:', error);
    throw error;
  }
};

/**
 * 更新用户的学习连续天数
 * 每日首次学习时调用，自动计算连续天数
 * @returns {Promise<Object>} 更新后的用户进度
 */
export const updateStreak = async () => {
  try {
    const currentProgress = await getUserProgress();
    const today = new Date();
    const todayString = today.toDateString();
    const lastStudyDate = currentProgress.lastStudyDate;
    
    let newStreak = currentProgress.currentStreak;
    let streakMessage = '';
    
    if (!lastStudyDate) {
      // 首次学习
      newStreak = 1;
      streakMessage = '开始你的学习之旅！';
    } else {
      const lastDate = new Date(lastStudyDate);
      const lastDateString = lastDate.toDateString();
      const yesterday = new Date(today);
      yesterday.setDate(yesterday.getDate() - 1);
      const yesterdayString = yesterday.toDateString();
      
      if (lastDateString === todayString) {
        // 今天已经学习过，不更改连续天数
        return currentProgress;
      } else if (lastDateString === yesterdayString) {
        // 昨天学习过，继续连续
        newStreak = currentProgress.currentStreak + 1;
        streakMessage = `太棒了！连续学习${newStreak}天！`;
      } else {
        // 连续中断，重新开始
        newStreak = 1;
        streakMessage = '连续中断了，但没关系，重新开始！';
      }
    }
    
    const updatedProgress = {
      ...currentProgress,
      currentStreak: newStreak,
      longestStreak: Math.max(newStreak, currentProgress.longestStreak),
      lastStudyDate: todayString,
      streakMessage // 用于显示给用户的消息
    };
    
    await updateUserProgress(updatedProgress);
    console.log(streakMessage);
    return updatedProgress;
  } catch (error) {
    console.error('更新学习连续天数失败:', error);
    throw error;
  }
};

/**
 * 完成课程的综合处理函数
 * 包括更新课程进度、添加XP、更新连续天数等
 * @param {number} lessonId - 课程ID
 * @param {number} xpEarned - 获得的经验值
 * @param {number} score - 课程得分（可选）
 * @returns {Promise<Object>} 更新后的用户进度
 */
export const completeLesson = async (lessonId, xpEarned, score = null) => {
  try {
    console.log(`开始处理课程 ${lessonId} 的完成情况...`);
    
    // 1. 更新课程进度
    await updateLessonProgress(lessonId, true, score);
    
    // 2. 添加经验值
    const progressAfterXP = await addXP(xpEarned);
    
    // 3. 更新学习连续天数
    const progressAfterStreak = await updateStreak();
    
    // 4. 更新完成课程数量
    const currentProgress = await getUserProgress();
    const updatedProgress = {
      ...currentProgress,
      ...progressAfterStreak,
      lessonsCompleted: currentProgress.lessonsCompleted + 1,
      totalXP: progressAfterXP.totalXP,
      level: progressAfterXP.level,
      lastCompletedLesson: {
        id: lessonId,
        completedAt: new Date().toISOString(),
        xpEarned,
        score
      }
    };
    
    await updateUserProgress(updatedProgress);
    
    // 5. 检查并解锁成就
    const newAchievements = await checkAchievements(updatedProgress);
    
    console.log(`课程 ${lessonId} 完成处理成功！`);
    
    return {
      ...updatedProgress,
      leveledUp: progressAfterXP.leveledUp,
      newAchievements: newAchievements.filter(ach => ach.unlocked && !ach.wasUnlocked)
    };
  } catch (error) {
    console.error('完成课程处理失败:', error);
    throw error;
  }
};

/**
 * 获取成就数据
 * @returns {Promise<Array>} 成就列表
 */
export const getAchievements = async () => {
  try {
    const achievementsData = await AsyncStorage.getItem(STORAGE_KEYS.ACHIEVEMENTS);
    return achievementsData ? JSON.parse(achievementsData) : achievements;
  } catch (error) {
    console.error('获取成就数据失败:', error);
    return achievements;
  }
};

/**
 * 检查并解锁成就
 * 根据用户当前进度检查是否满足成就解锁条件
 * @param {Object} userProgress - 用户进度数据
 * @returns {Promise<Array>} 更新后的成就列表
 */
export const checkAchievements = async (userProgress) => {
  try {
    const currentAchievements = await getAchievements();
    let achievementsUpdated = false;
    const newlyUnlocked = [];
    
    const updatedAchievements = currentAchievements.map(achievement => {
      if (achievement.unlocked) {
        return { ...achievement, wasUnlocked: true };
      }
      
      let shouldUnlock = false;
      
      // 根据不同的解锁条件检查
      switch (achievement.requirement) {
        case 'complete_lesson':
          shouldUnlock = userProgress.lessonsCompleted >= achievement.value;
          break;
        case 'streak':
          shouldUnlock = userProgress.currentStreak >= achievement.value;
          break;
        case 'xp':
          shouldUnlock = userProgress.totalXP >= achievement.value;
          break;
        case 'lessons_completed':
          shouldUnlock = userProgress.lessonsCompleted >= achievement.value;
          break;
        default:
          console.warn(`未知的成就解锁条件: ${achievement.requirement}`);
      }
      
      if (shouldUnlock) {
        achievementsUpdated = true;
        const unlockedAchievement = {
          ...achievement,
          unlocked: true,
          unlockedAt: new Date().toISOString(),
          wasUnlocked: false // 标记为新解锁
        };
        newlyUnlocked.push(unlockedAchievement);
        console.log(`解锁成就: ${achievement.title}`);
        return unlockedAchievement;
      }
      
      return achievement;
    });
    
    // 如果有新解锁的成就，保存到本地
    if (achievementsUpdated) {
      await AsyncStorage.setItem(STORAGE_KEYS.ACHIEVEMENTS, JSON.stringify(updatedAchievements));
      console.log(`新解锁 ${newlyUnlocked.length} 个成就`);
    }
    
    return updatedAchievements;
  } catch (error) {
    console.error('检查成就失败:', error);
    return currentAchievements || [];
  }
};

/**
 * 重置用户进度（用于开发和测试）
 * 删除所有本地存储的用户数据并重新初始化
 * @returns {Promise<void>}
 */
export const resetProgress = async () => {
  try {
    console.log('开始重置用户进度...');
    
    // 删除所有相关的存储数据
    await AsyncStorage.multiRemove([
      STORAGE_KEYS.USER_PROGRESS,
      STORAGE_KEYS.LESSONS_PROGRESS,
      STORAGE_KEYS.ACHIEVEMENTS
    ]);
    
    // 重新初始化默认数据
    await initializeUserProgress();
    
    console.log('用户进度重置成功');
  } catch (error) {
    console.error('重置用户进度失败:', error);
    throw new Error('无法重置用户进度，请稍后再试');
  }
};

/**
 * 获取学习统计数据
 * 修复了lessonsData引用错误，确保数据加载正常
 * @returns {Promise<Object>} 学习统计信息
 */
export const getStudyStats = async () => {
  try {
    const userProgress = await getUserProgress();
    const lessonsProgress = await getLessonsProgress();
    const achievements = await getAchievements();
    
    // 动态导入课程数据以避免循环依赖
    const { lessonsData } = await import('../data/lessons');
    
    // 计算学习统计
    const completedLessons = Object.values(lessonsProgress).filter(lesson => lesson.completed);
    const totalAttempts = Object.values(lessonsProgress).reduce((sum, lesson) => sum + (lesson.attempts || 0), 0);
    const unlockedAchievements = achievements.filter(ach => ach.unlocked);
    
    return {
      totalXP: userProgress.totalXP || 0,
      level: userProgress.level || 1,
      currentStreak: userProgress.currentStreak || 0,
      longestStreak: userProgress.longestStreak || 0,
      lessonsCompleted: completedLessons.length,
      totalLessons: lessonsData?.length || 6, // 默认课程数量
      completionRate: lessonsData?.length ? Math.round((completedLessons.length / lessonsData.length) * 100) : 0,
      totalAttempts,
      averageAttemptsPerLesson: completedLessons.length > 0 ? Math.round(totalAttempts / completedLessons.length) : 0,
      achievementsUnlocked: unlockedAchievements.length,
      totalAchievements: achievements.length,
      lastStudyDate: userProgress.lastStudyDate,
      studyDaysThisWeek: 0 // TODO: 计算本周学习天数
    };
  } catch (error) {
    console.error('获取学习统计失败:', error);
    // 返回默认统计数据而不是抛出错误
    return {
      totalXP: 0,
      level: 1,
      currentStreak: 0,
      longestStreak: 0,
      lessonsCompleted: 0,
      totalLessons: 6,
      completionRate: 0,
      totalAttempts: 0,
      averageAttemptsPerLesson: 0,
      achievementsUnlocked: 0,
      totalAchievements: 6,
      lastStudyDate: null,
      studyDaysThisWeek: 0
    };
  }
};